
import os
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class Message(db.Model):
    mstr = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):    
    def get(self):
        
        cmd = self.request.get('command')        
        if cmd == "hello": 
            name = self.request.get('name')
            
            if name == "":
                name = "No Name"
            
            tval = {
                'name': name
                }
            
            path = os.path.join(os.path.dirname(__file__), "index.html")
            self.response.out.write(template.render(path, tval))
        else:
            self.response.out.write("No Hello :(")
            

class MainForm(webapp.RequestHandler):
    
    def get(self):
        path = os.path.join(os.path.dirname(__file__), "form.html")
        
        query = db.GqlQuery("SELECT * FROM Message ORDER BY date DESC LIMIT 5")        
        tval = {"msgs": query}
        
        self.response.out.write(template.render(path, tval))
        
    def post(self):
        
        msg = Message(mstr=self.request.get("mesg"))
        msg.put()
                
        self.redirect('/myform')


def main():
    app = webapp.WSGIApplication([("/", MainPage)
                                  ,("/myform", MainForm)]
                                 ,debug=True
                                 )
    
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()